package com.sensetime.bi.senselink.server.rtsptest;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.Socket;
import java.util.TimerTask;

/**
 * Task that gets invoked after every 20 msec
 */
public class RtpPkgProcessTcp extends TimerTask {
    private RtspCtl ctl;
    BufferedInputStream in;
    byte[] data=new byte[1024];

    RtpPkgProcessTcp(RtspCtl ctl) {
        this.ctl = ctl;
        Socket rtspSocket = ctl.RTSPSocket;
        if (!rtspSocket.isClosed()) {

            try {
                in = new BufferedInputStream(rtspSocket.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    // Every 20 seconds, read from the socket connection
    public void run() {
        // Construct a DatagramPacket
        ctl.rcvdp = new DatagramPacket(ctl.buf, ctl.buf.length);
        Socket rtspSocket = ctl.RTSPSocket;
        if (!rtspSocket.isClosed()) {
            try {
                int len=0;
                while(-1!= (len = in.read(data, 0, data.length))) {
                    // Print out its length
                    System.out.println("Data Received by TCP: ");
                    String hexChars = bytesToHex(data, len);
                    System.out.println(hexChars);
                    System.out.println("TCP Length of data: " + len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // Convenience method to convert a byte array into a string
    // Source: http://stackoverflow.com/a/9855338/3250829
    // Tests shown to be the fastest conversion routine available
    // beating all other built-in ones in the Java API

    // For our byte to hex conversion routine
    final char[] hexArray = "0123456789ABCDEF".toCharArray();

    private String bytesToHex(byte[] bytes, int length) {
        char[] hexChars = new char[length * 2];
        for ( int j = 0; j < length; j++ ) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
}
